import re

from .check import CheckBasic
from ..report.log import logger


class Assertion(CheckBasic):
    '''
    断言类

    :Attribute:
     - ui_expect: 脚本的期望值
    '''

    def __init__(self, ui_expect):
        self.ui_expect = ui_expect

    def check_string(self, ui_value, error_info='期望值与界面取值不匹配！'):
        '''
        字符串检查

        :Args:
         - ui_value: 界面返回值
         - error_info: 错误信息

        :Raises:
            AssertionError: 字符串对比出错

        :Example:
         - 例: Assertion(ui_expect).check_string('新增成功')
        '''
        logger.debug('界面期望值为：' + str(self.ui_expect))
        logger.debug('界面取值为：' + str(ui_value))
        assert str(self.ui_expect) == str(ui_value), '界面取值为{}，期望值为{}，{}'.format(
                ui_value, self.ui_expect, error_info)
        logger.info('界面校验Pass')

    def match_string(self, ui_value, error_info='期望值与界面取值不匹配！'):
        '''
        字符串模糊匹配检查

        :Args:
         - ui_value: 界面返回值
         - error_info: 错误信息

        :Raises:
            AssertionError: 字符串不匹配

        :Example:
         - 例: Assertion(ui_expect).match_string('成功')
        '''
        logger.debug('界面期望值为：' + str(self.ui_expect))
        logger.debug('界面取值为：' + str(ui_value))
        if re.search(str(self.ui_expect), str(ui_value)):
            logger.info('界面校验Pass')
        else:
            raise AssertionError('界面取值为{}，期望值为{}，{}'.format(
                ui_value, self.ui_expect, error_info))

    def check_multiply_json(self, response: list):
        '''
        json数据校验，支持多组期望值校验，用于接口测试数据校验

        :Args:
         - response: json数据转化后的list

        :Example:
         - 例1: Assertion(ui_expect).check_multiply_json([{'name':'admin1','age':'24'},{'name':'admin2','age':'34'}])
         - 例2: Assertion(ui_expect).check_multiply_json({'name':'admin','age':'35'})
        '''
        if isinstance(self.ui_expect, dict):
            self.ui_expect = [self.ui_expect]
        logger.debug('接口期望值为：' + str(self.ui_expect))
        logger.debug('接口返回值为：' + str(response))
        if len(self.ui_expect) > len(response):
            raise AssertionError('校验数据多于返回数据，校验失败！')
        else:
            for expect in self.ui_expect:
                length = len(response)
                i = 0
                while i < len(response):
                    for key in expect.keys():
                        if key in response[i]:
                            if expect.get(key) != response[i].get(key):
                                i = i + 1
                                break
                        else:
                            i = i + 1
                            break
                    else:
                        response.remove(response[i])
                else:
                    if len(response) == length:
                        raise AssertionError(str(expect) + '该组校验数据不匹配！')
